import { useMenuOptions } from "@/models/global";
import { gutter } from "@/pages/const/keys";
import {
  getRoleDeptTree,
  getRoleInfo,
  updateRoleDataScope,
} from "@/services/role";
import { checkBoxGetValue } from "@/utils";
import {
  Card,
  Checkbox,
  Col,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Tree,
  TreeDataNode,
} from "antd";
import { Key, useEffect, useState } from "react";
type Props = {
  roleId: string;
  onClose?: (reflash: boolean) => void;
};
const App = (props: Props) => {
  const { roleId, onClose = () => {} } = props;
  const [form] = Form.useForm();
  const [roleInfo, setRoleInfo] = useState<API.RoleListItem>({});
  // 监听 watch form dataScope
  const dataScope = Form.useWatch("dataScope", form);
  const [menuTreeData, setMenuTreeData] = useState<TreeDataNode[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [expandedChecked, setExpandedChecked] = useState<boolean>(false);
  const getData = async () => {
    const { checkedKeys, depts, ...rest } = await getRoleDeptTree(roleId);
    const { data } = await getRoleInfo(roleId);
    const { roleKey, roleName, dataScope, menuCheckStrictly } = data || {};

    const allKes: ((prevState: Key[]) => Key[]) | any[] = [];
    const resetData = () => {
      const traverse = (nodes: TreeDataNode[]): TreeDataNode[] => {
        return nodes.map((node: any) => {
          const newNode: TreeDataNode = {
            key: node.id,
            title: node.label,
          };
          allKes.push(node.id);
          if (node.children) {
            newNode.children = traverse(node.children);
          }
          return newNode;
        });
      };
      return traverse(depts || []);
    };
    handleExpand(checkedKeys?.length > 0);
    setExpandedChecked(checkedKeys?.length > 0);
    setMenuTreeData(resetData() || []);
    if (checkedKeys?.length) {
      setExpandedKeys(allKes);
    }
    setCheckedKeys(checkedKeys);
    setRoleInfo(data);

    form.setFieldsValue({
      roleKey,
      roleName,
      dataScope,
      menuCheckStrictly,
      // menuIds: checkedKeys,
    });
  };
  const ok = async () => {
    const values = await form.validateFields();
    const { dataScope, menuCheckStrictly } = values || {};
    const deptIds = checkedKeys;
    const params = {
      ...roleInfo,
      dataScope,
      deptIds,
      menuCheckStrictly,
    };

    const res = await updateRoleDataScope({ ...params });
    console.log(params, res);
  };
  useEffect(() => {
    getData();
  }, []);
  // expand
  const handleExpand = (checked: boolean) => {
    const allKeys: any = [];
    const traverse = (nodes: TreeDataNode[]) => {
      nodes.forEach((node) => {
        console.log(node.key);
        allKeys.push(node.key as React.Key);
        if (node.children) {
          traverse(node.children);
        }
      });
    };

    traverse(menuTreeData);
    if (checked) {
      setExpandedKeys(allKeys);
    } else {
      setExpandedKeys([]);
    }
  };
  //selectall or unselect all
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      const allKeys: React.Key[] = [];
      const traverse = (nodes: TreeDataNode[]) => {
        nodes.forEach((node) => {
          allKeys.push(node.key as React.Key);
          if (node.children) {
            traverse(node.children);
          }
        });
      };
      traverse(menuTreeData);
      setCheckedKeys(allKeys);
    } else {
      setCheckedKeys([]);
    }
  };
  return (
    <Modal
      title="分配数据权限"
      open={true}
      onOk={ok}
      onCancel={() => {
        onClose(false);
      }}
    >
      <Form form={form}>
        <Form.Item label="角色名称" name="roleName">
          <Input disabled />
        </Form.Item>
        {/* 权限字符 */}
        <Form.Item label="权限字符" name="roleKey">
          <Input disabled />
        </Form.Item>
        {/* 权限范围 */}
        <Form.Item label="权限范围" name="dataScope">
          <Select
            options={[
              {
                value: "1",
                label: "全部数据权限",
              },
              {
                value: "2",
                label: "自定数据权限",
              },
              {
                value: "3",
                label: "本部门数据权限",
              },
              {
                value: "4",
                label: "本部门及以下数据权限",
              },
              {
                value: "5",
                label: "仅本人数据权限",
              },
            ]}
          />
        </Form.Item>
        {dataScope === "2" ? (
          <Form.Item label="菜单权限">
            <Row gutter={[gutter, gutter]}>
              <Col span={24} style={{ width: "100%" }}>
                <Row>
                  <Col>
                    <Checkbox
                      checked={expandedChecked}
                      onChange={(e) => {
                        handleExpand(e.target.checked);
                        setExpandedChecked(e.target.checked);
                      }}
                    >
                      展开/折叠
                    </Checkbox>
                  </Col>
                  <Col>
                    <Checkbox
                      onChange={(e) => {
                        handleSelectAll(e.target.checked);
                      }}
                    >
                      全选/反选
                    </Checkbox>
                  </Col>
                  <Col>
                    <Form.Item
                      name="menuCheckStrictly"
                      noStyle
                      valuePropName="checked"
                    >
                      <Checkbox>父子联动</Checkbox>
                    </Form.Item>
                  </Col>
                </Row>
              </Col>
              <Col span={24}>
                <Form.Item name="deptIds" noStyle>
                  <Card size="small">
                    <div
                      className="div"
                      style={{
                        height: 150,
                        overflow: "auto",
                      }}
                    >
                      <Tree
                        checkStrictly={true}
                        checkable
                        selectable={false}
                        //展开
                        defaultExpandAll
                        expandedKeys={expandedKeys}
                        checkedKeys={checkedKeys}
                        treeData={menuTreeData}
                        onExpand={(expandedKeys) => {
                          setExpandedKeys(expandedKeys);
                        }}
                        onCheck={(checkedKeys: any) => {
                          if (Array.isArray(checkedKeys.checked)) {
                            setCheckedKeys(checkedKeys.checked as React.Key[]);
                          }
                          // form.setFieldValue("menuIds", checkedKeys);
                        }}
                      />
                    </div>
                  </Card>
                </Form.Item>
              </Col>
            </Row>
          </Form.Item>
        ) : null}
      </Form>
    </Modal>
  );
};
export default App;
